package com.mmr.config;

import com.mmr.dxp.service.impl.DxpBlockChainSupportServiceImpl;
import com.mmr.util.ApplicationContextUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
@ChannelHandler.Sharable
@Slf4j
public class MyNettyServerHandler extends ChannelInboundHandlerAdapter {

    private static final String dxpSupportBean = DxpBlockChainSupportServiceImpl.class.getName();

    /**
     * 服务器端读取到 客户端发送过来的数据，然后通过 Channel 回写数据
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("服务器端读取到从客户端:{} 发送过来的数据：{}", ctx.channel().remoteAddress(), msg.toString());
        Assert.notNull(msg, "客户端发送消息为空");
        if (msg.toString().contains("::")) {
            String[] msgStr = msg.toString().split("::");
            String apiSign = msgStr[1];
            String apiData = msgStr[2];
            Class[] invokeParamClazz = ApplicationContextUtil.getClass(String.class);
            try {
                ApplicationContextUtil.getMethod(dxpSupportBean, apiSign, invokeParamClazz, apiData);
            } catch (Exception e) {
                e.printStackTrace();
                ctx.channel().writeAndFlush(String.format("server write:%s", "服务端处理失败：" + e.getMessage()));
            }
        }
    }

    /**
     * 捕获到异常的处理
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
